﻿using System;
using System.Collections.Generic;
using System.Linq;
using MB.TheBeerHouse.DAL;

namespace MB.TheBeerHouse.BLL.Articles
{
   public partial class tbh_Category : BaseArticleEntity
   {      
      public static IEnumerable<tbh_Category> GetCategories()
      {
         using (ArticlesDataContext context = GetContext())
         {
            return context.tbh_Categories.OrderByDescending(c => c.Importance).ThenBy(c => c.Title).ToList();
         }          
      }

      public static tbh_Category GetCategoryByID(int categoryID)
      {
         using (ArticlesDataContext context = GetContext())
         {
            return context.tbh_Categories.Where(c => c.CategoryID == categoryID).SingleOrDefault();
            // return context.tbh_Categories.SingleOrDefault(c => c.CategoryID == categoryID); // this works too!
         }         
      }

      public static void InsertCategory(tbh_Category category)
      {
         category.AddedDate = DateTime.Now;
         category.AddedBy = CurrentUserName;

         using (ArticlesDataContext context = GetContext())
         {
            context.tbh_Categories.InsertOnSubmit(category);
            context.SubmitChanges();
         }
      }

      public static void UpdateCategory(tbh_Category changedCategory)
      {
         using (ArticlesDataContext context = GetContext())
         {
            context.tbh_Categories.Attach(changedCategory, true);
            context.SubmitChanges();
         }
      }

      public static void DeleteCategory(tbh_Category category)
      {
         using (ArticlesDataContext context = GetContext())
         {
            context.tbh_Categories.Attach(category);
            context.tbh_Categories.DeleteOnSubmit(category);
            context.SubmitChanges();                        
         }
         new RecordDeletedEvent("category", category.CategoryID, null).Raise();
      }
   } 
}
